package fourfaith.com.ff_sl21_app.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fourfaith.com.ff_sl21_app.NoticeContentActivity;
import fourfaith.com.ff_sl21_app.R;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;

public class NoticeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{

    private static Context context;
    private NoticeAdapter mAdapter;

    private static SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private LinearLayoutManager mLayoutManager;
    private static LinearLayout load_layout;

    private LinearLayout progressBar, listLayout, dataError,dataEmpty;

    public static List<Map<String, Object>> data = new ArrayList<>();

    private OnFragmentInteractionListener mListener;

    /** 分页信息 */
    private static int pageStart = 0;
    private static int pageSize = 15;

    public NoticeFragment() {
        // Required empty public constructor
    }

    public static NoticeFragment newInstance(String param1, String param2) {
        NoticeFragment fragment = new NoticeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        context = getActivity();
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_notice,container,false);
        initView(view);
        swipeRefreshLayout.setRefreshing(true);
        getDataRequest();
        return view;
    }
    public void initView(View view){

        progressBar = (LinearLayout) view.findViewById(R.id.progressBar);
        listLayout = (LinearLayout) view.findViewById(R.id.listLayout);
        dataError = (LinearLayout) view.findViewById(R.id.dataError);
        dataEmpty = (LinearLayout) view.findViewById(R.id.dataEmpty);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new NoticeAdapter();
        recyclerView.setAdapter(mAdapter);
        recyclerView.addOnScrollListener(mOnScrollListener);

        //下拉刷新
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);

        // 设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(R.color.blue);

        swipeRefreshLayout.setOnRefreshListener(this);

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


    /**
     * 数据加载失败显示错误页面
     */
    public void showErrorPage() {
        progressBar.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataError.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);
    }

    /**
     * 数据加载中页面
     */
    public void showLoadingPage() {

        progressBar.setVisibility(View.VISIBLE);
        dataError.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
    }

    /**
     * 数据页面
     */
    public void showDataPage() {

        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);
    }

    /**
     * 空数据页面
     */
    public void showEmptyPage() {

        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.VISIBLE);
    }

    /**
     * 接口获取数据
     * @return
     */
    private void getDataRequest() {

        String userId = Constants.getUserId();

        String url = Constants.announceList +"?userId=" + userId + "&start="+pageStart + "&limit=" + pageSize;

        RequestQueue mQueue = RequestQueueSingleton.getInstance(context).getRequestQueue();
        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, url, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult responseResult) {

                        JSONArray dataArray = (JSONArray) responseResult.getData();
                        Map<String, Object> map;

                        if (dataArray != null && dataArray.size() > 0) {
                            for (int i = 0; i < dataArray.size(); i++) {

                                pageStart++;

                                JSONObject model = dataArray.getJSONObject(i);
                                map = new HashMap<>();

                                map.put("id",model.get("id"));
                                map.put("title",model.get("title"));
                                map.put("content",model.get("content"));
                                map.put("time",model.get("moditime"));
                                //0：未阅读;1：已阅读
                                map.put("isread",Integer.parseInt(String.valueOf(model.get("isread"))));

                                data.add(map);
                            }
                        }

                        mAdapter.notifyDataSetChanged();
                        if(data==null || data.size()==0){
                            showEmptyPage();
                        }else{
                            showDataPage();
                        }
                        finishRefreshing();
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                finishRefreshing();
                showErrorPage();
                if (error.networkResponse == null) {
                    Toast.makeText(context, "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (error.getMessage() == null) {
                        Toast.makeText(context, "接口服务器异常", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

            }

        });
        mQueue.add(jsonRequest);

    }

    // RecyclerView的滑动监听事件
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener()
    {
        private int lastVisibleItem;

        // 滑动状态改变
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState)
        {
            super.onScrollStateChanged(recyclerView, newState);
            /**
             * scrollState有三种状态，分别是SCROLL_STATE_IDLE、SCROLL_STATE_TOUCH_SCROLL、SCROLL_STATE_FLING
             * SCROLL_STATE_IDLE是当屏幕停止滚动时
             * SCROLL_STATE_TOUCH_SCROLL是当用户在以触屏方式滚动屏幕并且手指仍然还在屏幕上时
             * SCROLL_STATE_FLING是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
             */
            if ( newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == mAdapter.getItemCount()
                    && mAdapter.isShowFooter())
            {

                load_layout = (LinearLayout) getActivity().findViewById(R.id.load_layout);
                load_layout.setVisibility(View.VISIBLE);
                // 加载更多
                getDataRequest();
            }
        }

        // 滑动位置
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            super.onScrolled(recyclerView, dx, dy);
            // 给lastVisibleItem赋值
            // findLastVisibleItemPosition()是返回最后一个item的位置
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
        }
    };

    public static void finishRefreshing() {

        swipeRefreshLayout.setRefreshing(false);
        if(load_layout!=null) load_layout.setVisibility(View.GONE);
    }


    // 设置下拉刷新
    @Override
    public void onRefresh()
    {
        cleanData();
        mAdapter.notifyDataSetChanged();
        getDataRequest();
    }

    public static void cleanData(){
        pageStart = 0;
        data.clear();
    }

    class NoticeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
    {
        // 设置底部布局
        private static final int TYPE_FOOTER = 0;
        // 设置默认布局
        private static final int TYPE_DEFAULT = 1;
        // 判断是不是最后一个item，默认是true
        private boolean mShowFooter = true;

        @Override
        public RecyclerView.ViewHolder  onCreateViewHolder(ViewGroup parent, int viewType)
        {
            if (viewType == TYPE_DEFAULT)
            {
                View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_notice_item, parent, false);
                MyViewHolder vh = new MyViewHolder(v);
                return vh;
            } else
            {
                // 实例化布局
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_footer, null);
                // 代码实现加载布局
                view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                return new FooterViewHolder(view);
            }

        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            // 用来在运行时指出对象是某一个对象
            if (holder instanceof MyViewHolder) {
                final HashMap<String, Object> item = (HashMap) data.get(position);
                if (item == null) {
                    return;
                }

                //数据填充
                ((MyViewHolder) holder).title.setText(Constants.getString(item.get("title")));
                ((MyViewHolder) holder).content.setText("\u3000\u3000" + Constants.getString(item.get("content")));
                ((MyViewHolder) holder).time.setText(Constants.getString(item.get("time")));

                ((MyViewHolder) holder).noticeLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), NoticeContentActivity.class);
                        intent.putExtra("dataMap",item);
                        startActivity(intent);
                    }
                });
            }else{
            /*    if(7==(getItemCount()-1)){
                    ((FooterViewHolder)holder).more_data_msg.setText("已加载全部内容");
                }else{
                    ((FooterViewHolder)holder).more_data_msg.setText("正在加载");
                }*/
            }


        }

        // 设置不同的item
        @Override
        public int getItemViewType(int position)
        {
            // 判断当前位置+1是不是等于数据总数（因为数组从0开始计数），是的就加载底部布局刷新，不是就加载默认布局
            if (position + 1 == getItemCount())
            {
                return TYPE_FOOTER;
            } else
            {
                return TYPE_DEFAULT;
            }
        }

        @Override
        public int getItemCount()
        {
            // 判断是不是显示底部，是就返回1，不是返回0
            int begin = mShowFooter? 1 : 0;
            // 没有数据的时候，直接返回begin
            if (data == null)
            {
                return begin;
            }
            // 因为底部布局要占一个位置，所以总数目要+1
            return data.size() + begin;

        }
        // 设置是否显示底部加载提示（将值传递给全局变量）
        public void isShowFooter(boolean showFooter)
        {
            this.mShowFooter = showFooter;
        }

        // 判断是否显示底部，数据来自全局变量
        public boolean isShowFooter()
        {
            return this.mShowFooter;
        }
        // 底部布局的ViewHolder
        public class FooterViewHolder extends RecyclerView.ViewHolder
        {
            TextView more_data_msg;
            public FooterViewHolder(View view)
            {
                super(view);
                more_data_msg = (TextView) view.findViewById(R.id.more_data_msg);

            }
        }

        class MyViewHolder extends RecyclerView.ViewHolder
        {
            TextView title;
            TextView content;
            TextView time;
            LinearLayout noticeLayout;

            public MyViewHolder(View view)
            {
                super(view);
                title = (TextView) view.findViewById(R.id.title);
                content =  (TextView) view.findViewById(R.id.content);
                time =  (TextView) view.findViewById(R.id.time);
                noticeLayout = (LinearLayout)view.findViewById(R.id.noticeLayout);
            }
        }
    }
}
